<?php

namespace app\warehouse\logic;

use think\facade\Db;

class InStoresLogic extends BasicLogic
{

    /**
     * @desc   获取仓库商品列表
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function get_warehouse_sku($params=[]){
           $seller_sku = $params['seller_sku']??"";
           $limit      = getIsset($params,'limit',10);
           $where      = [];
           if($seller_sku){
               $where[]   =  ['seller_sku', 'like', '%' . $seller_sku . '%'];
           }
         $field = 'product_id,spu,product_name,seller_sku,image_info';
         $res   = Db::name('product_seller_sku')
               ->field($field)
               ->where($where)
               ->order(['created_time desc'])
               ->paginate($limit);
        $list = $res->items()?:[];
        $arr  = [];
        foreach($list as $k=>$v){
            $arr[$k]['spu']           = $v['spu'];
            $arr[$k]['product_id']    = $v['product_id'];
            $arr[$k]['seller_sku']    = $v['seller_sku'];
            if($v['image_info']){
                $arr[$k]['image_url'] = current(json_decode($v['image_info'],true));
            }else{
                $arr[$k]['image_url'] = $v['image_info'];
            }
            $arr[$k]['product_name']  = $v['product_name'] ? $v['product_name'] :'';
        }

        $data = [
            'list'                         => $arr,
            'total'                        => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取仓库商品匹配列表
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function get_warehouse_sku_import($params=[]){
       $in_stores = $params['in_stores']??'';
       if($in_stores){
               $this->jsonMessage(201,false,'入参数据不能为空!',null);
       }

        foreach($in_stores as $k=>$v){
            $spu_info  = explode('-', $v['seller_sku']);
            $spu       = $spu_info[0]??'';
            $arr[$k]['spu']           = $spu;
            $product_info             = Db::name('product')->field('product_name,product_images,id')->where(['spu'=>$spu])->find();
            $arr[$k]['product_id']    = $product_info['id'];
            $arr[$k]['seller_sku']    = $v['seller_sku'];
            $arr[$k]['in_stores_quantity']  = $v['in_stores_quantity'];
            if($product_info['product_images']){
                $arr[$k]['image_url'] = current(json_decode($product_info['product_images'],true));
            }else{
                $arr[$k]['image_url'] = '';
            }
            $arr[$k]['product_name']  = $product_info['product_name'] ?:'';
        }
        return  $this->jsonMessage(200,true,'获取成功',$arr);
    }









    /**
     * @desc   获取手动入库详情接口
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function get_in_stores($params){
          $in_number = $params['in_number']??'';
          $list      =  Db::name('warehouse_in_store_detail')
                        ->where(['in_number'=>$in_number])
                        ->select()
                        ->toArray();
          $basic_info = Db::name('warehouse_in_store')->where(['in_number'=>$in_number])->find();
          $data     = [
              'warehouse'   => '武汉江夏仓',
              'remark'      => $basic_info['remark']??'',
              'remark_color'=> $basic_info['remark_color']??'',
              'in_stores'   => $list,
          ];
          return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   创建入库单接口
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function add_in_stores($params=[]){
          $warehouse          = $params['warehouse']??'';
          $is_now_in          = $params['is_now_in']??'0';
          $in_number          = getInNumber();
          $add_json           = $params['in_stores']??'';
          if(!$add_json){
              $this->jsonMessage(201,false,'入参数据不能为空!',null);
          }

          if($is_now_in==1){ //入库
              $in_stores_status = 2;
          }

          $in_store_detail = [];
          foreach($add_json as $v){
                  $spu_info                    = explode('-', $v['seller_sku']);
                  $spu                         = $spu_info[0]??'';
                  $temp['in_number']           = $in_number;
                  $temp['spu']                 = $spu;
                  $temp['seller_sku']          = $v['seller_sku']??'';
                  $temp['warehouse_position']  = $v['warehouse_position']??'';
                  $temp['warehouse_partition'] = $v['warehouse_partition']??'';
                  $temp['warehouse_price']     = $v['warehouse_price']??'';
                  $temp['in_stores_quantity']  = $v['in_stores_quantity']??'1';
                  $temp['create_time']         = date('Y-m-d H:i:s',time());
                  $in_store_detail[]           = $temp;
          }
          $in_stores_quantity_all = array_sum(array_column($in_store_detail,'in_stores_quantity'));
          $current_info = current($in_store_detail);
          $spu_info     = explode('-', $current_info['seller_sku']);
          $spu          = $spu_info[0]??'';
          $in_store_arr = [
            'in_number'         =>$in_number,
            'spu'               =>$spu,
            'sku_nums'          =>count($in_store_detail),
            'in_stores_status'  =>$in_stores_status,
            'in_stores_quantity'=>$in_stores_quantity_all
          ];

          $params['spu']  = $spu;
          try {
            Db::startTrans(); // 开启事务
            Db::name('warehouse_in_store')->insert($in_store_arr);
            Db::name('warehouse_in_store_detail')->insertAll($in_store_detail);
            //同步入库仓库清单表;
            if($is_now_in==1){ //立即入库时才更新库存信息表
                self::add_stores_warehouse($params);
            }
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '新增成功', ''));
            $this->jsonMessage(200,true,'操作成功',null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }

    /**
     * @desc   编辑待入库接口
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function edit_in_stores($params=[]){
        $in_number          = $params['in_number']??'';
        $is_now_in          = $params['is_now_in']??'0';
        $add_json           = $params['in_stores']??'';
        if(!$add_json){
            $this->jsonMessage(201,false,'入参数据不能为空!',null);
        }

        if($is_now_in==1){ //入库
            $in_stores_status = 2;
        }else{
            $in_stores_status = 1;
        }

        foreach($add_json as $v){
            Db::name('warehouse_in_store_detail')->where(['in_number'=>$in_number,'seller_sku'=>$v['seller_sku']])->update(
                [
                    'warehouse_price'   => $v['warehouse_price']??'',
                    'in_stores_quantity'=> $v['in_stores_quantity']??'',
                    'create_time'       => date('Y-m-d H:i:s',time()),
                ]
            );
        }
        $in_stores_quantity_all = array_sum(array_column($add_json,'in_stores_quantity'));
        $current_info = current($add_json);
        $spu_info     = explode('-', $current_info['seller_sku']);
        $spu          = $spu_info[0]??'';
        $in_store_arr = [
            'in_stores_status'  =>$in_stores_status,
            'in_stores_quantity'=>$in_stores_quantity_all
        ];
        $params['spu']  = $spu;
        try {
            Db::startTrans(); // 开启事务
            Db::name('warehouse_in_store')->where(['in_number'=>$in_number])->update($in_store_arr);
            //同步入库仓库清单表;
            if($is_now_in==1){ //立即入库时才更新库存信息表
                self::add_stores_warehouse($params);
            }
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '编辑成功', ''));
            $this->jsonMessage(200,true,'操作成功',null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }


    /**
     * @desc   确认入库接口
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function ack_in_stores($params=[]){
        $in_number          = $params['in_number']??'';
        $add_json           = $params['in_stores']??'';
        if(!$add_json){
            $this->jsonMessage(201,false,'入参数据不能为空!',null);
        }

        $in_stores_status = 2;

        foreach($add_json as $v){
            Db::name('warehouse_in_store_detail')->where(['in_number'=>$in_number,'seller_sku'=>$v['seller_sku']])->update(
                [
                    'warehouse_price'   => $v['warehouse_price']??'',
                    'in_stores_quantity'=> $v['in_stores_quantity']??'',
                    'create_time'       => date('Y-m-d H:i:s',time()),
                ]
            );
        }
        $in_stores_quantity_all = array_sum(array_column($add_json,'in_stores_quantity'));
        $current_info = current($add_json);
        $spu_info     = explode('-', $current_info['seller_sku']);
        $spu          = $spu_info[0]??'';
        $in_store_arr = [
            'in_stores_status'  =>$in_stores_status,
            'in_stores_quantity'=>$in_stores_quantity_all
        ];
        $params['spu']  = $spu;
        try {
            Db::startTrans(); // 开启事务
            Db::name('warehouse_in_store')->where(['in_number'=>$in_number])->update($in_store_arr);
            //同步入库仓库清单表;
            self::add_stores_warehouse($params);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '编辑成功', ''));
            $this->jsonMessage(200,true,'操作成功',null);
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }



    /**
     * @desc   添加备注
     * @author luckyXiong
     * @date   2024-12-19
     */
    public function add_remark($params=[]){
        $id            = $params['id']??'';
        $remark        = $params['remark']??'';
        $remark_color  = $params['remark_color']??'1';

        Db::name('warehouse_in_store')->where(['id'=>$id])->update(
            [
                'remark'      =>$remark,
                'remark_color'=>$remark_color,
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   创建入库单接口
     * @author luckyXiong
     * @date   2024-12-16
     */
    public function getInStores($params=[]){
            $limit             = getIsset($params,'limit',10);
            $spu               = $params['spu']??'';
            $operate_id        = $params['operate_id']??'';
            $in_number         = $params['in_number']??'';
            $in_stores_status  = $params['in_stores_status']??'1';
            $remark            = $params['remark']??'';
            $create_time       = $params['create_time']??'';
            $where             = [];
            $where[] = ['in_stores_type','=',1];
            if($spu){
                 $where[] = ['spu', 'like', '%' . $spu . '%'];
            }

            if($operate_id){
                 $where[] = ['operate_id', '=',current(perate_id)];
            }

            if($remark){
                 $where[] = ['remark','like', '%' . $remark . '%'];
            }

            if($in_number){
                 $where[] = ['in_number','=',$in_number];
            }

            if($spu){
                 $where[] = ['spu', 'like', '%' . $spu . '%'];
            }

            if($in_stores_status){
                $where[] = ['in_stores_status', '=', $in_stores_status];
            }

            if ($create_time){
                 $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
                 $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
            }


            $res = Db::name('warehouse_in_store')
                  ->where($where)
                  ->order(['create_time desc'])
                  ->paginate($limit);
            $list = $res->items()?:[];

            $operater_ids = array_column($list,'operater_id');
            $spus         = array_column($list,'spu');

            //批量获取创建人;
            $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
            $admin_users_map = array_column($admin_users,null,'id');


            //批量获取图片地址;
            $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
            $products_map = array_column($products,null,'spu');
            foreach($list as $k=>$v){
                $admin_users_info             = $admin_users_map[$v['operater_id']]??'';
                $list[$k]['operater']         = $admin_users_info['username']??'';
                $product_images_product       = $products_map[$v['spu']]??[];
                $product_images               = $product_images_product['product_images']??[];
                $display_images               = $product_images ? current(json_decode($product_images)) : '';
                $list[$k]['image_url']        = $display_images;
            }

            $data = [
                'list'                         => $list,
                'total'                        => $res->total(),
            ];
            return  $this->jsonMessage(200,true,'获取成功',$data);

    }


    /**
     * @desc   获取手动入库详情列表接口
     * @author luckyXiong
     * @date   2024-12-17
     */
    public function getInStoresDetail($params=[]){
        $limit      = getIsset($params,'limit',10);
        $in_number  = $params['in_number']??'';
        $seller_sku = $params['seller_sku']??'';
        $create_time= $params['create_time']??'';
        $where      = [];
        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        if ($create_time){
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($in_number){
            $where[] = ['in_number', '=', $in_number];
        }

        $res = Db::name('warehouse_in_store_detail')
            ->where($where)
            ->order(['create_time desc'])
            ->paginate($limit);
        $list = $res->items()?:[];
        $spus         = array_column($list,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');

        foreach($list as $k=>$v){
            $product_images_product       = $products_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $list[$k]['image_url']        = $display_images;
        }
        $data = [
            'list'                        => $list,
            'total'                       => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   入库仓库清单表
     * @author luckyXiong
     * @date   2024-12-17
     */
    public function add_stores_warehouse($params=[])
    {
        $spu = $params['spu'];
        $product_info = Db::name('product')->where(['spu' => $spu])->find();
        $in_stores = $params['in_stores'] ?? '';
        $product_images_info = $product_info['product_images'] ?? [];
        $current_images = $product_images_info ? current(json_decode($product_images_info)) : '';
        foreach ($in_stores as $v) {
            $spu_info = explode('-', $v['seller_sku']);
            $spu = $spu_info[0] ?? '';
            $in_stores_quantity = $v['in_stores_quantity'] ?? 0;
            //查看seller_sku是否存在仓库;
            $exist_sku_inventory = Db::name('warehouse_sku_inventory')->where(['seller_sku' => $v['seller_sku']])->find();
            if ($exist_sku_inventory) {
                $inventory_quantity = $exist_sku_inventory['inventory_quantity'] + $in_stores_quantity;
                $all_inventory_quantity = $exist_sku_inventory['all_inventory_quantity'] + $in_stores_quantity;
                Db::name('warehouse_sku_inventory')
                    ->where(['id' => $exist_sku_inventory['id']])
                    ->inc()
                    ->update(
                    [
                        'inventory_quantity' => $inventory_quantity,
                        'all_inventory_quantity' => $all_inventory_quantity,
                        'update_time' => date('Y-m-d H:i:s', time()),
                    ]
                );
            } else {
                $insert_info = [
                    'spu'                     => $spu,
                    'seller_sku'              => $v['seller_sku'],
                    'product_name'            => $product_info['product_name'] ?? '',
                    'product_images'          => $current_images,
                    'inventory_quantity'      => $in_stores_quantity,
                    'all_inventory_quantity'  => $in_stores_quantity,
                    'warehouse'               => '武汉江夏仓',
                    'update_time'             => date('Y-m-d H:i:s', time()),
                    'create_time'             => date('Y-m-d H:i:s', time()),
                ];
                Db::name('warehouse_sku_inventory')->insert($insert_info);
            }
        }
    }


    /**
     * @desc   入库仓库清单表
     * @author luckyXiong
     * @date   2024-12-17
     */
    public function delete($params=[]){
        $id   = $params['id']??'';
        $info = Db::name('warehouse_in_store')->where(['id'=>$id])->find();
        Db::name('warehouse_in_store')->where(['id'=>$id])->delete();
        Db::name('warehouse_in_store_detail')->where(['in_number'=>$info['in_number']])->delete();
        return $this->jsonMessage(200,true,'操作成功!',null);
    }

    /**
     * @desc   获取退货入库列表接口
     * @author luckyXiong
     * @date   2024-12-19
     */
    public function getReStores($params=[]){
        $limit             = getIsset($params,'limit',10);
        $spu               = $params['spu']??'';
        $operate_id        = $params['operate_id']??'';
        $in_number         = $params['in_number']??'';
        $track_number      = $params['track_number']??'';
        $in_stores_status  = $params['in_stores_status']??'1';
        $package_number    = $params['package_number']??'0';
        $create_time       = $params['create_time']??'';
        $where             = [];

        $where[] = ['in_stores_type','=',2];
        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($operate_id){
            $where[] = ['operate_id', '=',current(operate_id)];
        }


        if($in_number){
            $where[] = ['in_number','=',$in_number];
        }

        if($track_number){
            $where[] = ['track_number','=',$track_number];
        }

        if($package_number){
            $where[] = ['package_number','=',$package_number];
        }

        if($in_stores_status){
            $where[] = ['in_stores_status', '=', $in_stores_status];
        }

        if ($create_time){
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        $res = Db::name('warehouse_in_store')
            ->where($where)
            ->order(['create_time desc'])
            ->paginate($limit);
        $list = $res->items()?:[];

        $operater_ids = array_column($list,'operater_id');
        $spus         = array_column($list,'spu');

        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');


        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        foreach($list as $k=>$v){
            $admin_users_info             = $admin_users_map[$v['operater_id']]??'';
            $list[$k]['operater']         = $admin_users_info['username']??'';
            $product_images_product       = $products_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $list[$k]['image_url']        = $display_images;
        }

        $data = [
            'list'                         => $list,
            'total'                        => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   获取退货入库列表接口
     * @author luckyXiong
     * @date   2024-12-19
     */
    public function getReStoresDetail($params){
        $limit      = getIsset($params,'limit',10);
        $in_number  = $params['in_number']??'';
        $seller_sku = $params['seller_sku']??'';
        $create_time= $params['create_time']??'';
        $where      = [];
        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        if ($create_time){
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($in_number){
            $where[] = ['in_number', '=', $in_number];
        }

        $res = Db::name('warehouse_in_store_detail')
            ->where($where)
            ->order(['create_time desc'])
            ->paginate($limit);
        $list = $res->items()?:[];
        $spus         = array_column($list,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');

        foreach($list as $k=>$v){
            $product_images_product       = $products_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $list[$k]['image_url']        = $display_images;
        }
        $data = [
            'list'                        => $list,
            'total'                       => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }










}